package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.util.List;

public class StudentSelectedCoursesController implements StudentSubController {

    @FXML
    private TableView<SelectedCourse> selectedCoursesTableView;
    @FXML
    private TableColumn<SelectedCourse, String> courseNameColumn;
    @FXML
    private TableColumn<SelectedCourse, Double> creditsColumn;
    @FXML
    private TableColumn<SelectedCourse, String> semesterColumn;

    private StudentController studentController;
    private User currentUser;
    private SelectedCourseDAO selectedCourseDAO;

    @Override
    public void setPrimaryStage(javafx.stage.Stage primaryStage) {
        // 不需要在这里设置primaryStage，由主控制器处理
    }

    @Override
    public void setStudentController(StudentController studentController) {
        this.studentController = studentController;
    }

    public void setCurrentUser(User user) {
        this.currentUser = user;
        System.out.println("StudentSelectedCoursesController: setCurrentUser called with user: " + (user != null ? user.getUsername() : "null"));
        // 在设置完 currentUser 后加载数据
        loadSelectedCourseData();
    }

    @FXML
    public void initialize() {
        // 初始化 DAO
        selectedCourseDAO = new SelectedCourseDAO();

        // 设置表格列与 SelectedCourse 对象的属性关联
        courseNameColumn.setCellValueFactory(new PropertyValueFactory<>("courseName"));
        creditsColumn.setCellValueFactory(new PropertyValueFactory<>("credits"));
        semesterColumn.setCellValueFactory(new PropertyValueFactory<>("semester"));

        // 表格数据将在 setCurrentUser 后加载
    }

    private void loadSelectedCourseData() {
        if (currentUser != null && selectedCourseDAO != null) {
            List<SelectedCourse> courses = selectedCourseDAO.getSelectedCoursesByStudentUsername(currentUser.getUsername());
            ObservableList<SelectedCourse> observableCourses = FXCollections.observableArrayList(courses);
            selectedCoursesTableView.setItems(observableCourses);
            System.out.println("Loaded " + courses.size() + " selected courses for user " + currentUser.getUsername());
        } else {
            System.err.println("currentUser or selectedCourseDAO is null. Cannot load selected course data.");
        }
    }
} 